#pragma once
#include <iostream>
#include <queue>
#include <vector>
#include <string>
#include <pthread.h>
#include "Thread.hpp"

const int default_thread_num = 5;

template <typename T> 
class ThreadPool {
private:
    void LockQueue() {
        pthread_mutex_lock(&_mutex);
    }

    void UnLockQueue() {
        pthread_mutex_unlock(&_mutex);
    }

    void WakeUpThread() {
        pthread_cond_signal(&_cond);
    }

    void SleepThread() {
        pthread_cond_wait(&_cond, &_mutex);
    }

    bool IsEmptyQueue() {
        return _task_queue.empty();
    }

    void HandlerTask(std::string name) {
        while (true) {
            LockQueue();
            while (IsEmptyQueue() && _isrunning) {
                // 只有当队列为空以及在运行的状态才会继续向下运行
                _sleep_thread_num++;
                SleepThread();
                _sleep_thread_num--;
            }
            // 当队列为空且不运行时自动退出
            if (IsEmptyQueue() && !_isrunning) {
                std::cout << name << " quit..." << std::endl;
                UnLockQueue();
                break;
            }
            // 运行到这个位置任务队列中一定有元素，且愿意运行下去
            T t = _task_queue.front();
            _task_queue.pop();

            // t 执行任务
            std::cout << name << " -> " << t.result() << std::endl;
            UnLockQueue();
        }
    }

public:
    ThreadPool(int threadnum = default_thread_num)
        : _thread_num(default_thread_num),
          _sleep_thread_num(0),
          _isrunning(false)
    {
        // pthread_mutex_init(_mutex, nullptr);
        pthread_mutex_init(&_mutex, nullptr);
        // pthread_cond_init(_cond, nullptr);
        pthread_cond_init(&_cond, nullptr);
    }

    void Init() {
        func_t func = std::bind(&ThreadPool::HandlerTask, this, std::placeholders::_1);
        for (int i = 0; i < _thread_num; i++) {
            std::string name = "thread-" + std::to_string(i + 1);
            _threads.emplace_back(func, name);
        }
    }

    void Start() {
        _isrunning = true;
        for (auto& thread : _threads)
            thread.Start();
    }

    void Stop() {
        LockQueue();
        _isrunning = false;
        pthread_cond_broadcast(&_cond);
        UnLockQueue();
    }

    void Push(const T& in) {
        LockQueue();
        if (_isrunning) {
            _task_queue.push(in);
            if (_sleep_thread_num > 0)
                WakeUpThread();
        }
        UnLockQueue();
    }

    ~ThreadPool() {
        for (auto& t : _threads)
            t.Join();
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_cond);
    }

private:
    int _thread_num;
    int _sleep_thread_num;
    std::vector<Thread> _threads;
    std::queue<T> _task_queue;

    bool _isrunning;
    pthread_mutex_t _mutex;
    pthread_cond_t _cond;
};